/**
 * @description 目录文件-服务
 * @since 2019-11-12
 * @author Rid King
*/

const ox = require('@daelui/oxjs')
const Model = require('./model.js')
const PoolModel = require('../pool/model.js')
const { FileDB } = require('@daelui/oxjs/dist/file-db.js')
// 添加文件存储
ox.dbFactory.addDB('file', {
  type: 'file',
  class: FileDB
})

class Service extends ox.Service {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 模型
    this.$model = new Model(args)
  }

  /**
   * @function 查询所有数据
   * @param {Object} action 操作集合
   * @demo
   * {
   *  req: {Request}
   *  res: {Response}
   *  data: {Object}
   * }
   * @return {Array}
  */
  async queryAll (action) {
    let result = []
    let params = action.params || {}
    let path = params.path
    let isFindAll = params.isFindAll
    let ignoreDir = params.ignoreDir
    let ignoreFile = params.ignoreFile
    // 指定路径
    if (path) {
      result = {
        data: [
          {
            path: path,
            isFindAll: isFindAll !== undefined ? isFindAll : true,
            ignoreDir: ignoreDir !== undefined ? ignoreDir : '',
            ignoreFile: ignoreFile !== undefined ? ignoreFile : ''
          }
        ]
      }
    } else {
      // 目录模型
      let $model = new PoolModel({route: this.route})
      result = await $model.where({
        excute: {
          operators: [
            {field: 'id', operator: 'EQUAL'}
          ],
          sort: [
            {field: 'order', by: 'desc'}
          ]
        },
        params: {
          id: action.params.pid || -9999
        }
      }).find()
    }
    // 目录数据
    let data = result.data
    if (data && data.length > 0) {
      let path = data[0].path
      path = String(path).replace(/\/*\.+\/*/g, '').replace(/^\/+/g, '')
      if (path) {
        let constant = this.route.scope.CONFIG.constant
        let resPath = constant.poolPath + '/res'
        action.excute = action.excute || {}
        Object.assign(action.excute, {
          dataSource: {
            url: resPath + '/' + path,
            table: '',
            isFindAll: isFindAll !== undefined ? isFindAll : true,
            ignoreDir: ignoreDir !== undefined ? ignoreDir : undefined,
            ignoreFile: ignoreFile !== undefined ? ignoreFile : undefined,
            isIncludeDir: true,
            isIncludeRoot: false
          },
          sort: [
            {field: 'createTime', by: 'desc'},
            {field: 'updateTime', by: 'desc'}
          ]
        })
        action.params = {
          name: action.params.name,
          pageIndex: action.params.pageIndex,
          pageSize: action.params.pageSize
        }
        result = await this.$model.find(action)
      } else {
        result.data = []
      }
    } else {
      result.data = []
    }

    return result
  }
}

module.exports = Service